<template>
  <div v-if="visible">
    <JModal
      :title="title"
      :width="width"
      :fullscreen="true"
      :canFullscreen="true"
      v-model:open="visible"
      cancelText="关闭"
      :okButtonProps="{ style: { display: 'none' } }"
      :cancelButtonProps="{ style: { display: 'none' } }"
    >
      <component :is="bbb" v-bind="routeProps" />
    </JModal>
  </div>
  <div v-if="visibleiframe" v-loading="loadingiframe">
    <JModal
      :title="title"
      :width="width"
      :fullscreen="true"
      :canFullscreen="true"
      v-model:open="visibleiframe"
      cancelText="关闭"
      :okButtonProps="{ style: { display: 'none' } }"
      :cancelButtonProps="{ style: { display: 'none' } }"
    >
      <iframe ref="iframedraftr" :src="externalUrl" frameborder="0" style="width: 100%; height: 100%" @load="onIframeLoaded"></iframe>
    </JModal>
  </div>
  <div class="management-page">
    <div class="filter-container">
      <a-form layout="inline" :model="filterForm">
        <a-form-item name="radio-button" label="">
          <a-radio-group v-model:value="filterForm.schernum" @change="schernumchange">
            <a-radio-button type="primary" value="a">我的已办</a-radio-button>
            <a-radio-button type="primary" value="b">竞签已办</a-radio-button>
            <a-radio-button type="primary" value="c">代理已办</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="">
          <a-select v-model:value="filterForm.status" style="width: 200px" placeholder="请选择" @change="handleFilterChange" defaultValue="RUNNING">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="endorsement">加签</a-select-option>
            <a-select-option value="general">同意</a-select-option>
            <a-select-option value="submit">提交</a-select-option>
            <a-select-option value="revoke">撤回</a-select-option>
            <a-select-option value="voteAgainst">反对</a-select-option>
            <a-select-option value="rollBackTaskByExpression">拒绝</a-select-option>
            <a-select-option value="terminationProcess">作废</a-select-option>
            <a-select-option value="rejectAndTerminate">终止</a-select-option>
            <a-select-option value="transfer">转办</a-select-option>
            <a-select-option value="tempSave">暂存</a-select-option>
            <a-select-option value="manualSkipNode">自动跳过</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-input v-model:value="filterForm.subject" placeholder="流程名称，任务主题，申请人" style="width: 250px" @pressEnter="handleSearch" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon><SearchOutlined /></template>
            查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset"> 重置 </a-button>
        </a-form-item>
      </a-form>
    </div>
    <div style="height: 30px; display: flex; justify-content: space-between; /* align-content: center; */ align-items: center">
      <div style="font-size: 16px">{{ '已办任务' }}</div>
    </div>
    <div class="table-container">
      <a-table
        :key="tableKey"
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        bordered
        @change="handleTableChange"
        :customRow="handleRowClick"
        rowKey="task_instance_id"
      >
        <template #create_time="{ record }">
          <div class="create_time-cell"> {{ formatTimestamp(record.create_time) }} </div>
        </template>
        <template #exist_time="{ record }">
          <div class="exist_time-cell"> {{ calculateTimeDiff(record.exist_time) }} </div>
        </template>
        <template #node_name="{ record }">
          <div class="node_name-cell">
            <div>{{ record.node_name }} </div>
            <div>{{ formatTimestamp(record.create_time) }} </div>
          </div>
        </template>
        <template #applicant="{ record }">
          <div class="applicant-cell">
            <a-avatar
              size="small"
              style="margin-right: 8px; background-color: #1890ff"
              :src="record.initiator.avatar_url ? record.initiator.avatar_url : ''"
            >
              {{ record.initiator.avatar_url ? '' : record.initiator.employee_name.slice(0, 2) }}
            </a-avatar>
            <div>
              <div>{{ (record.initiator.department_name || '-') + '-' + (record.initiator.employee_name || '-') }}</div>
            </div>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed, defineAsyncComponent } from 'vue';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import axios from 'axios';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { donelist, competitionlist, agentlist } from './user.api';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  const API_DOMAIN = import.meta.env.VITE_GLOB_DOMAIN_URL;
  const iframedraftr = ref(null);
  const loadingiframe = ref(true);
  const title = ref('已办');
  const width = ref(800);
  const disableSubmit = ref(false);
  const visibleiframe = ref(false);
  const externalUrl = ref('');
  const filters = ref({});
  const tableRef = ref(null);
  const filtersch = ref('');
  const tableKey = ref(0);
  const forceReset = () => {
    tableKey.value += 1;
  };
  const onIframeLoaded = () => {
    loadingiframe.value = false;
    toggleIframe(visibleiframe.value);
  };
  const toggleIframe = (data) => {
    if (iframedraftr.value?.contentWindow) {
      iframedraftr.value.contentWindow.postMessage(data, '*');
    }
  };
  const { createConfirm, createMessage } = useMessage();
  // 表格列定义
  const columns = computed(() => [
    {
      title: '流程标题',
      dataIndex: 'subject',
      key: 'subject',
      ellipsis: true,
    },
    {
      title: '流程类型',
      dataIndex: 'process_type',
      key: 'process_type',
      filters: filters.value.filtersall,
      filterMode: 'tree',
      filterSearch: false,
      ellipsis: true,
    },
    {
      title: '审批状态',
      dataIndex: 'command_name',
      key: 'command_name',
      ellipsis: true,
    },
    {
      title: '在手人',
      dataIndex: 'applicant',
      key: 'applicant',
      slots: { customRender: 'applicant' },
      ellipsis: true,
    },
    {
      title: '在手时长',
      dataIndex: 'exist_time',
      key: 'exist_time',
      slots: { customRender: 'exist_time' },
      sorter: (a, b) => a.exist_time - b.exist_time,
      ellipsis: true,
    },

    // {
    //   title: '上一审批人',
    //   dataIndex: 'applicant',
    //   key: 'applicant',
    //   slots: { customRender: 'applicant' },
    // },
    {
      title: '发起人',
      dataIndex: 'applicant',
      key: 'applicant',
      slots: { customRender: 'applicant' },
      ellipsis: true,
    },
    {
      title: '发起时间',
      dataIndex: 'create_time',
      key: 'create_time',
      slots: { customRender: 'create_time' },
      sorter: (a, b) => a.create_time - b.create_time,
      ellipsis: true,
    },
  ]);

  // 筛选表单数据
  const filterForm = reactive({
    schernum: 'a',
    status: '',
    subject: '',
  });
  const router = useRouter();
  const visible = ref(false);
  const targetRouteName = ref(''); // 目标路由名称
  const routeParams = ref();
  const bbb = ref();
  // 从路由配置中获取组件
  const currentComponent = computed(() => {
    const route = router.resolve({ path: targetRouteName.value });
    console.log(route, targetRouteName.value, 180);

    return route.matched[1]?.components?.default;
  });

  // 手动构造路由props
  const routeProps = ref();

  const showModal = () => {
    visible.value = true;
  };
  // 表格数据
  const tableData = ref([]);

  const loading = ref(false);
  const selectedRowKey = ref([]);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
  });

  // 初始化加载数据
  onMounted(() => {
    fetchData('1');
    window.addEventListener('message', handleiframe);
  });

  const handleiframe = (event) => {
    if (event.data.type === 'VISIBLE_UPDATED') {
      console.log('iframe 状态已更新:', event.data.visible);
      visibleiframe.value = event.data.visible;
    }
  };
  const calculateTimeDiff = (timestamp) => {
    const seconds = Math.floor(timestamp / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    

    return `${days}天-${hours % 24}时-${minutes % 60}分-${seconds % 60}秒`;
  };
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  let aa = null;
  const handleRowClick = (record, index) => {
    return {
      onClick: (event) => {
        console.log(record, index, event, '11111111111111111111111111111111111111111111');

        if (!event.target.closest('.ant-table-selection-column')) {
          event.preventDefault();
          event.stopPropagation();

          if (!record.relative_url.includes('/apps/api/v1/private/form/dispatcher') && record.relative_url.startsWith('/')) {
            if (record.relative_url.includes('154/')) {
              console.log(record.relative_url, 154);
            }
            title.value = record.subject;
            const queryString = record.relative_url.split('?')[1];
            const keyValuePairs = queryString.split('&');
            const result = {};
            keyValuePairs.forEach((pair) => {
              const [key, value] = pair.split('=');
              result[key] = decodeURIComponent(value); // 处理URL编码字符
            });
            routeProps.value = result;
            const route = router.resolve({ path: record.relative_url, query: result });
            console.log(route, 190);
            let asynccom = route.matched[1]?.components?.default;
            console.log(asynccom, 263);
            if (asynccom === undefined) {
              createMessage.error('未找到该审批页组件,请注册组件');
              return;
            }
            bbb.value = defineAsyncComponent(asynccom);
            visible.value = true;
          } else {
            // const localUrl = window.location.origin;
            // console.log(localUrl, 198);
            const url = record.open_url.split('//')[1];
            const urlnow = url.substring(url.indexOf('/') + 1);
            externalUrl.value = '/' + urlnow;
            console.log(externalUrl.value, 303);
            visibleiframe.value = true;
            loadingiframe.value = true;
          }
        }
      },
    };
  };

  // 获取数据方法
  const fetchData = async (ifone) => {
    try {
      loading.value = true;

      // 调用listall接口
      const data = {
        page: {
          page_index: pagination.current,
          page_size: pagination.pageSize,
        },
        query: {
          time_sort: 'desc',
          status: '',
          subject: filterForm.subject ? filterForm.subject : '',
          type_key_list: filtersch.value,
          command_type: filterForm.status,
        },
      };
      let response;
      if (filterForm.schernum === 'a') {
        console.log(1);
        response = await donelist(data);
      } else if (filterForm.schernum === 'b') {
        console.log(2);
        response = await competitionlist(data);
      } else {
        console.log(3);
        response = await agentlist(data);
      }
      if (response.code === '000000') {
        const currentTime = new Date().getTime();
        console.log(currentTime, 239);

        tableData.value = response.data.rows;
        tableData.value.forEach((item) => {
          item['exist_time'] = item.end_time - item.create_time;
        });
        pagination.total = response.data.page.total;
        const filtersall = response.data.rows
          .filter((item, index, self) => self.findIndex((i) => i.process_type === item.process_type) === index)
          .map((item) => {
            return { text: item.process_type, value: item.process_definition_key };
          });
        if (ifone === '1') {
          filters.value.filtersall = filtersall;
        }
        console.log(filters.value, tableData.value, '222222222222222222222222222222222222');
      } else {
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      console.error('获取数据出错:', error);
      message.error('获取数据出错');
    } finally {
      loading.value = false;
    }
  };

  // 筛选条件变化处理
  const handleFilterChange = () => {
    pagination.current = 1; // 重置到第一页
    console.log(238, 'handleFilterChange');

    fetchData();
  };

  // 搜索处理
  const handleSearch = () => {
    pagination.current = 1;
    console.log(245, 'handleSearch');

    fetchData();
  };

  // 重置处理
  const handleReset = () => {
    filterForm.status = '';
    filterForm.subject = '';
    filterForm.schernum = 'a';
    pagination.current = 1;
    filters.value.filtersall = [];
    filtersch.value = '';
    forceReset();
    fetchData('1');
  };
  const schernumchange = () => {
    console.log(318);
    filterForm.status = '';
    filterForm.subject = '';
    pagination.current = 1;
    filters.value.filtersall = [];
    filtersch.value = '';
    forceReset();
    fetchData('1');
  };
  // 表格变化处理（分页、排序）
  const handleTableChange = (pag, filters, sorter) => {
    pagination.current = pag.current;
    pagination.pageSize = pag.pageSize;
    // 这里可以处理排序逻辑
    console.log(filters, sorter, 260);
    if (JSON.stringify(filters) !== '{}') {
      const filtersstr = filters?.process_type.join(',');
      filtersch.value = filtersstr;
    }
    console.log(filtersch.value, 285);
    fetchData();
  };

  // 处理按钮点击
  const handleProcess = (record) => {
    console.log('处理记录:', record);
    message.info(`处理流程: ${record.name}`);
  };

  // 详情按钮点击
  const agreebacklog = () => {
    createConfirm({
      iconType: 'warning',
      title: '确认操作',
      content: '是否审批选中数据?',
      onOk: async () => {
        try {
          loading.value = true;

          const data = selectedRowKey.value.map((item) => ({ agent_id: item.initiator.employee_id, task_instance_id: item.task_instance_id }));

          const response = await backlogagree(data);
          if (response.code === '000000') {
            console.log(response);
            createMessage.success('操作成功');
            fetchData();
          } else {
            message.error(response.data.message || '获取数据失败');
          }
        } catch (error) {
          message.error('获取数据出错');
        } finally {
          loading.value = false;
        }
      },
    });
  };
</script>

<style scoped>
  .management-page {
    padding: 16px;
    background: #fff;
    min-height: 100%;
  }

  .filter-container {
    padding: 16px;
    border-radius: 4px;
  }

  .table-container {
    border: 1px solid #f0f0f0;
    border-radius: 4px;
  }

  .applicant-cell {
    display: flex;
    align-items: center;
  }

  :deep(.ant-table) {
    font-size: 14px;
  }

  :deep(.ant-table-thead > tr > th) {
    background-color: #fafafa;
    font-weight: 500;
  }

  :deep(.ant-table-tbody > tr > td) {
    padding: 12px 16px;
  }

  :deep(.ant-btn-link) {
    padding: 0 4px;
  }
</style>
